const express = require('express')
const Router = express.Router()
const utils = require('utility')
const model = require('./model')
const User = model.getModel('user')
const Chat = model.getModel('chat')

const _filter = {pwd: 0, __v: 0}

Chat.remove({},function(e,d){});

Router.get('/list', function (req, res) {
  // User.remove({}, function (e, d) { })
  const {type} = req.query;
  User.find({type}, function (err, doc) {
    return res.json({code: 0, data: doc})
  })
})

Router.get('/getmsglist', function(req, res) {
  const user = req.cookies.userid;
  User.find({}, function(e, userdoc) {
    let users = {};
    userdoc.forEach(v => {
      users[v._id] = { name: v.user, avatar: v.avatar };
    });
    Chat.find({'$or': [{ from: user }, { to: user }]}, function(err, doc) {
      if (!err) {
        return res.json({code: 0, msgs: doc, users: users});
      };
    });
  })
})

Router.post('/readMsg', function(req, res) {
  const userid = req.cookies.userid;
  const { from } = req.body;
  Chat.update(
    { from, to: userid },
    { read: true },
    { multi: true },
    function(err, doc) {
      if (!res.err) {
        return res.json({code: 0, num: doc.nModified});
      }
      return res.json({code: 1, msg: '修改失败'});
    }
  );
})

Router.post('/update', function (req, res) {
  const userid = req.cookies.userid;
  if (!userid) {
    return res.json.dumps({code: 1});
  }
  const body = req.body;
  User.findByIdAndUpdate(userid, body, function(err, doc) {
    const data = Object.assign({}, {
      user: doc.user,
      type: doc.type
    }, body);
    return res.json({code: 0, data});
  })
})

Router.post('/login', function (req, res) {
  const { user, pwd } = req.body
  User.findOne({ user, pwd: md5Pwd(pwd) }, _filter, function (err, doc) {
    if (!doc) {
        return res.json({ code: 1, msg: '用户名或密码错误' })
    }
    //将用户的id种到浏览器的cookie中
    res.cookie('userid', doc._id);
    return res.json({ code: 0, data: doc })
  })
})

Router.post('/register', function (req, res) {
  const { user, pwd, type } = req.body
  //检查用户名是否已存在
  User.findOne({ user }, function (err, doc) {
    if (doc) {
      return res.json({ code: 1, msg: '用户名重复' })
    }
  })
  //如果用户名不存在，那么新建此条用户
  const userModel = new User({ user, type, pwd: md5Pwd(pwd) });
  userModel.save(function (err, doc) {
    if (err) {
      return res.json({code: 1, msg: '后台出错了'});
    }
    const {user, type, _id} = doc;
    res.cookie("userid", _id);
    return res.json({ code: 0, data: {user, type, _id} });
  });

    // User.create({ user, type, pwd: md5Pwd(pwd) }, function (err, doc) {
    //     if (err) {
    //         return res.json({ code: 1, msg: '后台出错了' })
    //     }
    //     const {user, type, _id} = doc;
    //     res.cookie("userid", _id);
    //     return res.json({ code: 0, data: doc })
    // })

})

Router.get('/info', function (req, res) {
  //用户有没有cookie
  const {userid} = req.cookies;
  if(!userid) {
    return res.json({code: 1});
  }
  User.findOne({_id: userid}, _filter, function(err, doc) {
    if(err) {
      return res.json({code: 1, msg: '后端出错了！'});
    }
    if(doc) {
      return res.json({code: 0, data: doc});
    }
  });
})

//为加密密码加盐
function md5Pwd(pwd) {
  let salt = 'ghostlpx@$#%kdjfs__+==='
  return utils.md5(pwd + salt)
}

module.exports = Router